﻿using System;
using System.Runtime.Remoting.Messaging;
using System.Text;
using GestorSQL.Utility;

namespace AspectIntercept
{
    public class ConsoleTraceProcessor : IPreProcessor, IPostProcessor
    {
        private string _MethodCall = string.Empty;
        private string _MethodResult = string.Empty;

        #region IPreProcessor Members

        public void Process(ref IMethodCallMessage msg)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Método: {0} Argumentos:", msg.MethodName);
            for (int i = 0; i < msg.InArgCount; i++)
                sb.AppendFormat("{0}{1}", msg.InArgs[i].ToXml(true), ((i + 1) < msg.InArgCount ? "," : ""));
            _MethodCall = sb.ToString();
            msg.Properties.Add("_MethodCall", _MethodCall);
        }

        #endregion

        #region IPostProcessor Members

        public void Process(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg)
        {
            StringBuilder sb = new StringBuilder();
            Exception e = retMsg.Exception;
            if (e != null)
            {
                sb.AppendFormat("Exception: {0}", e.ToString());
            }
            else
            {
                sb.AppendFormat("Retorno: {0}", retMsg.ReturnValue);
                for (int i = 0; i < retMsg.OutArgCount; i++)
                    sb.AppendFormat("{0}{1}", retMsg.OutArgs[i], ((i + 1) < retMsg.OutArgCount ? "," : ""));
            }
            _MethodResult = sb.ToString();
            _MethodCall = callMsg.Properties["_MethodCall"].ToString();
            Console.WriteLine(_MethodCall);
            Console.WriteLine(_MethodResult);
        }

        #endregion
    }
}
